package cc.rengu.redp.bizimpl.upmp.controller;


import cc.rengu.redp.bizimpl.enums.PageOptFlagEnum;
import cc.rengu.redp.bizimpl.upmp.common.BusinessContainer;
import cc.rengu.redp.bizimpl.upmp.domain.*;
import cc.rengu.redp.bizimpl.upmp.service.*;
import cc.rengu.redp.bizimpl.upmp.vo.OperationResult;
import cc.rengu.redp.bizimpl.upmp.vo.UpmpUserInfoVO;
import cc.rengu.redp.bizimpl.utils.Common;
import cc.rengu.redp.bizimpl.utils.CommonUtils;
import cc.rengu.redp.common.controller.BaseController;
import cc.rengu.redp.common.domain.QueryRequest;
import cc.rengu.redp.common.exception.RedpException;
import com.alibaba.fastjson.JSON;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.beanutils.BeanMap;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.xssf.streaming.SXSSFCell;
import org.apache.poi.xssf.streaming.SXSSFRow;
import org.apache.poi.xssf.streaming.SXSSFSheet;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import sun.misc.BASE64Encoder;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.UUID;

/**
 * @author 刘玉亮.LL
 */
@Api(tags = "商户管理:拓展经理管理")
@Slf4j
@RestController
@RequestMapping(value = "/admin/merParam/managerInfo")
public class ManagerInfoController extends BaseController {

    private long oprMenuId = 20000020;
    private String oprMenuName = "商户管理:拓展经理管理";
    private long chkMenuId = 20000020;
    private String chkMenuName = "商户管理:拓展经理管理";
    private String webNextUrl = "/admin/merParam/managerInfo/edit";

    @Autowired
    private IManagerInfoService managerInfoService;

    @Autowired
    private IUpmpOrganizationService organizationsService;

    @Autowired
    private IAgentInfoService agentInfoService;

    @Autowired
    private RegionInfoService regionInfoService;
    @Autowired
    private IUpmpSysParamService upmpSysParamService;


    //@RequiresPermissions("商户管理:拓展经理管理")
    @GetMapping(value = "/list")
    @ApiOperation(value = "列表查询")
    public Map<String, Object> findByPage(QueryRequest request, ManagerInfo info) {
        return getDataTable(managerInfoService.findByPage(request, info));
    }


    //@RequiresPermissions("商户管理:拓展经理管理")
    @GetMapping(value = "/edit")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", name = "optFlag", value = "操作类型", required = true, dataType = "String")
    })
    public Map editShow(@ModelAttribute("managerInfo") ManagerInfo entity, Model model, HttpServletRequest request) throws RedpException {
        java.util.Map<String, Object> result = com.google.common.collect.Maps.newHashMap();
        String optFlag = request.getParameter("optFlag") == null ? "" : request.getParameter("optFlag");
        UpmpUserInfoVO user = CommonUtils.getCurrentUser(upmpSysParamService);

        SimpleDateFormat fmtdt = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
        String lastUpddt = fmtdt.format(new Date());
        String areaName = "";
        String signInstName = "";
        // 增加
        if ("add".equals(optFlag)) {
            String instId = request.getParameter("instId") == null ? "" : request.getParameter("instId");
            String crtOrgId = "";
            if (user.isAdmin()) {
                if (StringUtils.isEmpty(instId)) {
                    log.error("运营中心管理员新增数据必须先选择法人行！");
                    throw new RedpException("运营中心管理员新增数据必须先选择法人行！");
                } else {
                    UpmpOrganization headOrg = organizationsService.getHeadOrgByCode(instId);
                    crtOrgId = (headOrg == null ? user.getOrgCode() : headOrg.getOrgCode());
                }
            } else {
                instId = (instId == null ? user.getInstId() : instId);
                crtOrgId = user.getOrgCode();
            }
            UpmpOrganization org = organizationsService.getOrgByCode(crtOrgId, instId);
            entity.setId("0");
            entity.setInstId(org.getInstId());
            entity.setOprId(user.getId());
            entity.setCrtOrgId(org.getOrgCode());
            entity.setCreateTime(lastUpddt);
            entity.setOpenId("0");
            entity.setUserStatus("00");
        }
        // 修改，注销，停用，启用，详情，审批
        if ("upd".equals(optFlag) || "view".equals(optFlag) || "cancel".equals(optFlag)) {
            String id = request.getParameter("id") == null ? "" : request.getParameter("id");
            if (!"".equals(id)) {
                entity = managerInfoService.getById(id);
                if (entity.getSignInstType().equals("BANK")) {
                    entity.setSignInstIdOrg(entity.getSignInstId());
                } else {
                    entity.setSignInstIdAgent(entity.getSignInstId());
                }

            }
        }
       result.put("optFlag", optFlag);
        result.put("entity", entity);
        return result;
    }

    

    //@RequiresPermissions("商户管理:拓展经理管理")
    @PostMapping(value = "/edit")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", name = "optFlag", value = "操作类型", required = true, dataType = "String")
    })
    public OperationResult editSave(@ModelAttribute("managerInfo") ManagerInfo entity, Model model, HttpServletRequest request) throws RedpException {
        String optFlag = request.getParameter("optFlag") == null ? "" : request.getParameter("optFlag");
        UpmpUserInfoVO user = CommonUtils.getCurrentUser(upmpSysParamService);
        UpmpOrganization org = organizationsService.getOrgByCode(user.getOrgCode(), user.getInstId());
        java.util.Map<String, Object> result = com.google.common.collect.Maps.newHashMap();
        SimpleDateFormat fmtdt = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
        String lastUpddt = fmtdt.format(new Date());

        //校验 手机号 与 工号，状态为已注销的记录忽略
        if (PageOptFlagEnum.OPT_FLAG_ADD.getType().equals(optFlag)) {
            List<ManagerInfo> mIdList = managerInfoService.findManagerInfoByManagerId(entity.getManagerId());
            if (null != mIdList && mIdList.size() > 0) {
                return OperationResult.buildFailureResult("工号已存在");
            }

            List<ManagerInfo> phoneList = managerInfoService.findManagerInfoByManagerPhone(entity.getManagerPhone(), entity.getInstId());
            if (null != phoneList && phoneList.size() > 0) {
                return OperationResult.buildFailureResult("手机号已存在");
            }
        } else if (PageOptFlagEnum.OPT_FLAG_UPDATE.getType().equals(optFlag)) {
            List<ManagerInfo> mIdList = managerInfoService.findManagerInfoByManagerId(entity.getManagerId());
            if (null != mIdList) {
                if (mIdList.size() == 1) {
                    if (!mIdList.get(0).getId().equals(entity.getId())) {
                        return OperationResult.buildFailureResult("工号已存在");
                    }
                } else if (mIdList.size() > 1) {
                    return OperationResult.buildFailureResult("工号已存在");
                }
            }

            List<ManagerInfo> phoneList = managerInfoService.findManagerInfoByManagerPhone(entity.getManagerPhone(), entity.getInstId());
            if (null != phoneList) {
                if (phoneList.size() == 1) {
                    if (!phoneList.get(0).getId().equals(entity.getId())) {
                        return OperationResult.buildFailureResult("手机号已存在");
                    }
                } else if (phoneList.size() > 1) {
                    return OperationResult.buildFailureResult("手机号已存在");
                }
            }
        }
        entity.setLastOprId(user.getId());
        entity.setLastUpdateTime(lastUpddt);

        String menuId;
        if (PageOptFlagEnum.OPT_FLAG_CHECK.getType().equals(optFlag)) {
            menuId = String.valueOf(chkMenuId);
        } else {
            menuId = String.valueOf(oprMenuId);
        }
        return managerInfoService.saveData(menuId, oprMenuName, entity, request, webNextUrl);
    }


    //@RequiresPermissions("商户管理:拓展经理管理")
    @PostMapping(value = "/upload")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", name = "instId", value = "机构标识", required = true, dataType = "String"),
            @ApiImplicitParam(paramType = "query", name = "upload", value = "上传的文件", required = true, dataType = "String")
    })
    @ApiOperation(value = "批量导入")
    public OperationResult uploadSave(@RequestParam(value = "excelFile", required = false) MultipartFile excelFile, Model model, HttpServletRequest request) throws RedpException {
        java.util.Map<String, String> result = com.google.common.collect.Maps.newHashMap();
        String instId = request.getParameter("instId");
        String path = request.getSession().getServletContext().getRealPath("upload");
        if (StringUtils.isBlank(excelFile.getOriginalFilename())) {
            return OperationResult.buildFailureResult("请选择导入文件");
        }
       UpmpSysParam dataDict = upmpSysParamService.findChildrenByPrimaryKeyAndParent("MCHNT_IMPORT_PARAM", BusinessContainer.SYS_IMPORT_EXPORT_PARAM, instId, null);
        if (Common.isBlank(dataDict)) {
            log.error("解析文件时获取系统参数失败，请联系系统管理员");
            throw new RedpException("解析文件时获取系统参数失败，请联系系统管理员");
        }
        if (Common.isBlank(dataDict.getPrimaryValue())) {
            log.error("解析文件时获取系统参数值失败，请联系系统管理员");
            throw new RedpException("解析文件时获取系统参数值失败，请联系系统管理员");
        }
        Map sysparam = (Map) JSON.parse(dataDict.getPrimaryValue());
        int maxRecords = Common.isBlank(sysparam.get("MAX_RECORDS")) ? Integer.valueOf(sysparam.get("MCHNT_IMPORT_MAX_RECORDS").toString()) : Integer.valueOf(sysparam.get("MAX_RECORDS").toString());
        String fileName = UUID.randomUUID().toString() + "_" + excelFile.getOriginalFilename();
        String filePath = path + File.separator + fileName;
        File targetFile = new File(path, fileName);
        if (!targetFile.exists()) {
            targetFile.mkdirs();
        }

        try {
            excelFile.transferTo(targetFile);    //保存
        } catch (Exception e) {
            targetFile.delete();
            log.error(e.getMessage());
        }

        try {
            List<ManagerInfo> list = managerInfoService.getManagerInfoFromXls(filePath, maxRecords, result);
            if (Common.isNotBlank(result.get("uploadErrMsg"))) {
                return OperationResult.buildFailureResult(result.get("uploadErrMsg"));
            }
            for (ManagerInfo managerInfo : list) {
                managerInfo.setInstId(instId);
            }
            //校验并保存
            result = managerInfoService.batchSave(String.valueOf(oprMenuId), oprMenuName, list, request, webNextUrl);
        } catch (Exception e) {
            log.error(e.getMessage());
            return OperationResult.buildFailureResult("数据保存失败");
        } finally {
            targetFile.delete();
        }
        if (result.get("status").equals("success")) {
            log.info("数据保存处理完成,成功保存" + result.get("value") + "条数据");
           return OperationResult.buildFailureResult("数据保存处理完成,成功保存" + result.get("value") + "条数据");
        } else {
            log.error(result.get("msg") + ",错误数据<" + result.get("value") + ">");
            return OperationResult.buildFailureResult(result.get("msg") + ",错误数据<" + result.get("value") + ">");
        }
    }


    //@RequiresPermissions("商户管理:拓展经理管理")
    @RequestMapping(value = "/getTemplate")
    public void getExcel(HttpServletRequest request, HttpServletResponse response) throws RedpException {
        try {
            String filename = "拓展经理导入模板.xlsx";
            response.setCharacterEncoding("UTF-8");
            response.setHeader("Content-Disposition", "attachment;filename=" + filename);
            String header = request.getHeader("User-Agent");
            if (header.toLowerCase().contains("firefox")) {
                BASE64Encoder base64Encoder = new BASE64Encoder();
                response.setHeader("Content-Disposition", "attachment; filename==?UTF-8?B?" + (new String(base64Encoder.encode(filename.getBytes("UTF-8")))) + "?=");
            } else {
                response.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(filename, "UTF-8"));
            }
            response.setContentType("application/vnd.ms-excel;charset=UTF-8");
            OutputStream os = response.getOutputStream();

            SXSSFWorkbook wb = new SXSSFWorkbook();//创建Excel工作簿对象
            SXSSFSheet sheet = (SXSSFSheet) wb.createSheet("拓展经理信息");//创建Excel工作表对象

            // 创建Excel的sheet的第一行,即列头
            SXSSFRow hssfFirstRow = (SXSSFRow) sheet.createRow(0);
            String[] title = {"员工号", "姓名", "手机号", "拓展经理角色", "收单机构类型", "收单机构代码", "地区代码-省", "地区代码-市", "地区代码-区","","除了地区代码外都是必填项"};

            for (int i = 0; i < title.length; i++) {
                String cell = title[i];
                // 创建一个Excel的单元格
                SXSSFCell hssfCell = (SXSSFCell) hssfFirstRow.createCell(i);
                hssfCell.setCellValue(cell);
            }
            wb.write(os);
            IOUtils.closeQuietly(os);
        } catch (Exception e) {
            throw new RedpException("拓展经理管理导出异常："+e.getMessage());
        }
    }

    @GetMapping(value = "/organizationSelect2List")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", name = "q", value = "参数", required = true, dataType = "String")
    })
    public  Map<String,Object>  agentmanageorgSelect2List(QueryRequest request,UpmpOrganization q) {
        return organizationsService.organizationSelect2List(request,q);

    }


    //@RequiresPermissions("商户管理:拓展经理管理")
    @RequestMapping(value = "/gridExport")
    public void gridExportAll(HttpServletRequest request, HttpServletResponse response) throws RedpException {
        List<Map> rows = null;
        try {
            rows =  managerInfoService.exportList(request);
        } catch (Exception e) {
            throw new RedpException("导出数据出现异常"+ e.getCause());
        }

        try {
            String filename = "拓展经理信息.xlsx";
            response.setCharacterEncoding("UTF-8");
            response.setHeader("Content-Disposition", "attachment;filename=" + filename);
            response.setContentType("application/vnd.ms-excel;charset=UTF-8");
            OutputStream os = response.getOutputStream();

            SXSSFWorkbook wb = new SXSSFWorkbook();//创建Excel工作簿对象
            SXSSFSheet sheet = (SXSSFSheet) wb.createSheet("拓展经理信息");//创建Excel工作表对象

            // 创建Excel的sheet的第一行,即列头
            SXSSFRow hssfFirstRow = (SXSSFRow) sheet.createRow(0);
            String[] title = {"银行代码", "拓展经理角色", "姓名", "手机号", "员工号", "收单机构类型", "收单机构", "地区代码", "操作状态"};
            for (int i = 0; i < title.length; i++) {
                String cell = title[i];
                // 创建一个Excel的单元格
                SXSSFCell hssfCell = (SXSSFCell) hssfFirstRow.createCell(i);
                hssfCell.setCellValue(cell);
            }
            for (int i = 0; i < rows.size(); i++) {
                Object row = rows.get(i);
                Map rowMap = null;
                if (!(row instanceof Map)) {
                        rowMap = new BeanMap(row);
                } else {
                    rowMap = (Map) row;
                }
                if (null != rowMap && !rowMap.isEmpty()) {
                    // 创建Excel的sheet的一行
                    SXSSFRow hssfRow = (SXSSFRow)sheet.createRow(i + 1);
                    // 创建Excel的单元格
                    SXSSFCell cell0 = (SXSSFCell) hssfRow.createCell(0);
                    cell0.setCellValue((String) rowMap.get("INSTID"));
                    SXSSFCell cell1 = (SXSSFCell) hssfRow.createCell(1);
                    String roletype = (String) rowMap.get("ROLETYPE");
                    if ("40".equals(roletype)) {
                        roletype = "拓展经理";
                    }else if("41".equals(roletype)){
                        roletype = "拓展经理审核员";
                    }
                    cell1.setCellValue(roletype);
                    SXSSFCell cell2 = (SXSSFCell) hssfRow.createCell(2);
                    cell2.setCellValue((String) rowMap.get("MANAGERNAME"));
                    SXSSFCell cell3 = (SXSSFCell) hssfRow.createCell(3);
                    cell3.setCellValue((String) rowMap.get("MANAGERPHONE"));
                    SXSSFCell cell4 = (SXSSFCell) hssfRow.createCell(4);
                    cell4.setCellValue((String) rowMap.get("MANAGERID"));
                    SXSSFCell cell5 = (SXSSFCell) hssfRow.createCell(5);
                    String signInstType = (String) rowMap.get("SIGNINSTTYPE");
                    if ("BANK".equals(signInstType)) {
                        signInstType = "银行";
                    }else if("AGENT".equals(signInstType)){
                        signInstType = "代理商";
                    }
                    cell5.setCellValue(signInstType);
                    SXSSFCell cell6 = (SXSSFCell)hssfRow.createCell(6);
                    String signinstName = "";
                    if ("银行".equals(signInstType)) {
                        signinstName = (String) rowMap.get("ORGNAME");
                    } else if ("代理商".equals(signInstType)) {
                        signinstName = (String) rowMap.get("AGENTNAME");
                    }
                    cell6.setCellValue(signinstName);
                    SXSSFCell cell7 = (SXSSFCell) hssfRow.createCell(7);
                    cell7.setCellValue((String) rowMap.get("AREANAME"));
                    SXSSFCell cell8 = (SXSSFCell) hssfRow.createCell(8);
                    String userStatus = (String) rowMap.get("USERSTATUS");
                    if ("00".equals(userStatus)) {
                        userStatus = "正常";
                    }else if("01".equals(userStatus)){
                        userStatus = "注销";
                    }
                    cell8.setCellValue(userStatus);
                }
            }
            wb.write(os);
            IOUtils.closeQuietly(os);
        } catch (Exception e) {
            throw new RedpException("拓展经理管理导出异常："+e.getMessage());
        }
    }
}
